import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:inmotion_pro/config/const.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';
import 'package:pin_code_fields/pin_code_fields.dart';

import '../../../../../l10n/local.dart';
import '../../../../../utils/string_util.dart';
import '../../../../mixin/account_security_mixin.dart';
import '../../../../models/user_model.dart';
import 'controller.dart';

class VerifyCodeView extends BaseGetView<VerifyCodeController>
    with AccountSecurityMixin {
  VerifyCodeView({super.key});

  @override
  Widget build(BuildContext context) {
    return DismissKeyboardScaffold(
      resizeToAvoidBottomInset: false, // 防止键盘弹出时页面内容被顶起
      child: Scaffold(
        appBar: AppBar(
          title: const SizedBox.shrink(),
          leading: CommonWidgets.appBarLeading(onTap: () {
            Get.back();
          }),
          // 可选：移除默认的返回按钮阴影
          automaticallyImplyLeading: false,
        ),
        body: Container(
          padding: EdgeInsets.symmetric(horizontal: 32.w, vertical: 40.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 标题和描述
              _buildHeader(context),
              SizedBox(height: 40.w),

              // 验证码输入区域
              _buildPinCodeField(context),
              SizedBox(height: 24.w),

              // 倒计时和重新获取
              _buildCountdownSection(context),
              SizedBox(height: 32.w),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildHeader(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        LxText(
          local.please_enter_verification_code,
          fontWeightEnum: LxFontWeightEnum.headlineLarge,
        ),
        const SizedBox(height: 12),
        LxText(
          local.verification_code_sent_to_account(controller
                      .state.param.platform ==
                  CodePlatform.phone
              ? LxStringUtil.obscurePhone(controller.state.param.account ?? '')
              : LxStringUtil.obscureEmail(
                  controller.state.param.account ?? '')),
          fontWeightEnum: LxFontWeightEnum.bodyMedium,
          lineHeight: 1.5,
          color: Colors.white.withOpacity(0.6),
        ),
      ],
    );
  }

  // 构建验证码输入框
  Widget _buildPinCodeField(BuildContext context) {
    return Obx(
      () => Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(16),
          color: Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.3),
          border: Border.all(
            color: controller.state.hasError.value
                ? Theme.of(context).colorScheme.error
                : Colors.transparent,
            width: 1.5,
          ),
        ),
        padding: EdgeInsets.all(CONTENT_MARGIN),
        child: Column(
          children: [
            PinCodeTextField(
              length: verificationCodeLength,
              cursorColor: LxCol.theme,
              obscureText: false,
              animationType: AnimationType.fade,
              animationDuration: const Duration(milliseconds: 300),
              enableActiveFill: true,
              keyboardType: TextInputType.number,
              autoFocus: true,
              textStyle: Theme.of(context).textTheme.headlineSmall?.copyWith(
                    fontWeight: FontWeight.w600,
                    color: controller.state.hasError.value
                        ? Theme.of(context).colorScheme.error
                        : Theme.of(context).colorScheme.onBackground,
                  ),
              pinTheme: PinTheme(
                shape: PinCodeFieldShape.underline,
                borderRadius: BorderRadius.circular(8),
                fieldHeight: 60,
                fieldWidth: 40,
                activeFillColor: Colors.transparent,
                activeColor: controller.state.hasError.value
                    ? Theme.of(context).colorScheme.error
                    : Theme.of(context).primaryColor,
                selectedFillColor: Colors.transparent,
                selectedColor: controller.state.hasError.value
                    ? Theme.of(context).colorScheme.error
                    : Theme.of(context).primaryColor,
                inactiveFillColor: Colors.transparent,
                inactiveColor: controller.state.hasError.value
                    ? Theme.of(context).colorScheme.error
                    : Colors.grey.shade400,
                errorBorderColor: Theme.of(context).colorScheme.error,
              ),
              onChanged: (value) {
                controller.verifyCode(value);
              },
              onCompleted: (value) {},
              appContext: context,
            ),
          ],
        ),
      ),
    );
  }

  // 构建倒计时和重新获取部分
  Widget _buildCountdownSection(BuildContext context) {
    return Obx(() => Center(
          child: controller.state.countdownTime.value > 0
              ? Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.access_time_filled,
                      size: 16,
                      color: Theme.of(context).colorScheme.primary,
                    ),
                    const SizedBox(width: 6),
                    Text.rich(
                      TextSpan(
                        children: [
                          TextSpan(
                            text:
                                '(${controller.state.countdownTime.value}${local.sec}) ',
                            style: Theme.of(context)
                                .textTheme
                                .bodyMedium
                                ?.copyWith(
                                  color: Theme.of(context).colorScheme.primary,
                                  fontWeight: FontWeight.bold,
                                ),
                          ),
                          TextSpan(
                            text: local.resend_code,
                            style: Theme.of(context).textTheme.bodyMedium,
                          ),
                        ],
                      ),
                    ),
                  ],
                )
              : MouseRegion(
                  cursor: SystemMouseCursors.click,
                  child: GestureDetector(
                    onTap: () {
                      controller.resendCodeOnTap();
                    },
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 16, vertical: 8),
                      decoration: BoxDecoration(
                        color: Theme.of(context).colorScheme.primary,
                        borderRadius: BorderRadius.circular(20),
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Icon(
                            Icons.refresh,
                            size: 16,
                            color: Theme.of(context).colorScheme.onPrimary,
                          ),
                          const SizedBox(width: 6),
                          Text(
                            local.resend_code,
                            style: Theme.of(context)
                                .textTheme
                                .bodyMedium
                                ?.copyWith(
                                  color:
                                      Theme.of(context).colorScheme.onPrimary,
                                  fontWeight: FontWeight.w500,
                                ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
        ));
  }
}
